from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.http.response import JsonResponse
from django.core.mail import send_mail

from blog.models import Blog
from .models import CaptchaModel
from .forms import RegisterForm, LoginForm
from django.views.decorators.http import require_http_methods
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.models import User
import string
import random


# 登录
@require_http_methods(['GET', 'POST'])
def sy_login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                # 判断是否需要记住我
                if not remember:
                    # 如果没有点击记住我，那么就要设置过期时间为0，即浏览器关闭后就会过期
                    request.session.set_expiry(0)
                # 如果点击了，那么就什么都不做，使用默认的2周的过期时间
                return redirect('/')
            else:
                print('邮箱或密码错误！')
                # form.add_error('email', '邮箱或者密码错误！')
                # return render(request, 'login.html', context={"form": form})
                return redirect(reverse('blog_user:login'))


# 退出登录
@require_http_methods(['GET'])
def sy_logout(request):
    logout(request)
    return redirect(reverse('blog_user:login'))


# 注册
@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(username=username, email=email, password=password)
            return redirect(reverse('blog_user:login'))
        else:
            print(form.errors)
            # 重新跳转到注册页面
            return redirect(reverse('blog_user:register'))


# 发送邮箱验证码
def send_email_captcha(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'code': 400, 'message': '邮箱不能为空'})
    # 生成验证码（4位数字）
    captcha = "".join(random.sample(string.digits, 4))
    # 存储在数据库，根据邮箱查找，如果存在就更新，不存在就创建
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
    send_mail("首义博客注册验证码", message=f"您的验证码是：{captcha}", recipient_list=[email], from_email=None)
    return JsonResponse({'code': 200, 'message': '发送成功'})


# 我的博客
@require_http_methods(['GET'])
def my_blog(request):
    if request.user.is_authenticated:
        blogs = Blog.objects.filter(author=request.user)
        return render(request, 'my_pub_blog.html', context={'blogs': blogs})
    else:
        return redirect(reverse('blog_user:login'))


# 删除博客

def delete_blog(request, blog_id):
    # 根据blog_id获取Blog对象
    blog = get_object_or_404(Blog, id=blog_id)

    # 删除Blog对象
    blog.delete()

    # 返回JSON响应
    return JsonResponse({'status': 'success', 'message': '博客已成功删除'})
